package com.ttxz.common.base.view

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.hjq.toast.ToastUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.impl.LoadingPopupView
import com.ttxz.common.BaseApplication
import com.ttxz.common.base.model.BaseModel
import com.ttxz.common.base.viewmodel.BaseViewModel
import org.joor.Reflect
import java.lang.reflect.ParameterizedType

/**
 * 简要说明
 *
 * @author ttxz
 * @date 2022/6/10 15:36
 */
open class BaseActivity<VB : ViewBinding, VM> :
    FragmentActivity() where VM : BaseViewModel<BaseModel> {
    lateinit var viewBinding: VB
    lateinit var viewModel: VM
    private var mLoadingPopup: LoadingPopupView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        createVB()
        createVM()
        registerDefaultUILiveData()
        registerUILiveData() //初使化和事件监听注册完成，VM可以执行数据相关的操作
        viewModel.initData()
        initCustomData()
    }

    /**
     * 注册LiveData事件，和VM通讯
     */
    protected open fun registerUILiveData() {
        //默认空实现
    }

    /**
     * 初使化完成VM和VB后，可以初使化相关元素和逻辑
     */
    protected open fun initCustomData() {
        //默认空实现
    }

    override fun onDestroy() {
        super.onDestroy()
        //释放loading框资源
        if (mLoadingPopup != null) {
            if (mLoadingPopup!!.isShow) {
                mLoadingPopup!!.dismiss()
            }
            mLoadingPopup!!.onDestroy()
        }
    }

    /**
     * 创建ViewBinding
     */
    private fun createVB() {
        val viewClass: Class<*>
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            viewClass = type.actualTypeArguments[0] as Class<*>
            viewBinding = Reflect.onClass(viewClass).call("inflate", layoutInflater).get()
            setContentView(viewBinding!!.root)
        }
    }

    /**
     * 创建ViewModel
     */
    private fun createVM() {
        val type = javaClass.genericSuperclass
        val modelClass = if (type is ParameterizedType) {
            type.actualTypeArguments[1] as Class<VM>
        } else { //如果没有指定泛型参数，则默认使用BaseViewModel
            BaseViewModel::class.java
        }
        viewModel =
            ViewModelProvider.AndroidViewModelFactory.getInstance(BaseApplication.Instance.mApplication)
                .create(modelClass) as VM //viewModel绑定View事件
        viewModel.let {
            lifecycle.addObserver(it)
        }
    }

    /**
     * 注册默认的通用LiveData事件
     */
    private fun registerDefaultUILiveData() {
        viewModel.showLoadingEvent.observeForever { aBoolean: Boolean ->
            if (aBoolean) {
                if (mLoadingPopup == null) {
                    mLoadingPopup = XPopup.Builder(this).asLoading("正在加载中")
                }
                mLoadingPopup!!.show()
            } else {
                mLoadingPopup!!.dismiss()
            }
        }
        viewModel.showToastEvent.observeForever { text: String? -> ToastUtils.show(text) }
        viewModel.switchActivityEvent.observeForever { aClass: Class<*>? ->
            startActivity(Intent(this, aClass))
            if (isFinishActivity) {
                finish()
            }
        }
    }

    /**
     * 跳转界面的时候，是否要关闭此界面，
     * @return `true` 关闭， `false` 不关闭
     */
    protected val isFinishActivity: Boolean
        protected get() = true
}